<?php
ArrowController::importModel("org.arrowplatform.model.IArrowDataSource");
ArrowController::importModel("org.arrowplatform.model.ArrowModelField");  
class ArrowDataSource implements IArrowDataSource{
	private $model;
	private $class;
	private $actions = array();
	private $criteria;
	public function __construct( $model , $actions = array() ){
		$this->model = $model;
		ArrowController::importModel( $model );
		$arr = explode( ".", $model );
		$className = array_pop($arr);
		$this->class = $className;
		$this->actions = $actions;
	}
	public function getFields(){
		$fields = Persistent::getClassFieldnames($this->class);
		$tmp = array();
		foreach( $fields as $key => $val )
			$tmp[] = new ArrowModelField( $key, $key );
		return $tmp;
	}
	public function getList($criteria){
		if($criteria instanceof ArrowOrmJoinCriteria)
			return call_user_func( array($this->class, "getDataSetByCriteria"), $criteria, $this->class);
		return call_user_func( array($this->class, "getByCriteria"), $criteria, $this->class);
		
	}
	public function countList( $criteria){
		$criteria = clone $criteria;
		$criteria->setEmptyList();
		$criteria->removeOrder();
		$criteria->addColumn("id", "" , Criteria::A_COUNT);
		if( $criteria->isGroupBy() ) {
				$criteria->clearLimit();
				Persistent::turnOnQueryMode();
				$result = call_user_func( array($this->class, "getByCriteria"), $criteria, $this->class );
				Persistent::turnOffQueryMode();
				if($criteria instanceof  ArrowOrmJoinCriteria)
					$result = ArrowOrmSqlRouter::toArray( ArrowOrmSqlRouter::query("select count(`{$this->class}:id`) as sum from ({$result}) as tmp"));
				else
					$result = ArrowOrmSqlRouter::toArray( ArrowOrmSqlRouter::query("select count(`id`) as sum from ({$result}) as tmp"));
					
				if( $result[0]["sum"] == "null" ) return 0 ;
					
				return $result[0]["sum"];
				
		} else {
			$criteria->setLimit(0,1);
			$result = call_user_func( array($this->class, "getByCriteria"), $criteria, $this->class);
			if(isset($result[0][$this->class])) {
				return $result[0][$this->class]["id"];
			} else {
				return $result[0]["id"];
			}
		}
	}
	public function getModel(){
		return $this->model;
	}
	public function getModelInstance( $key ){
		return Persistent::getByKey($key, $this->class);
	}
	public function getListActions(){
		return $this->actions;
	}
	public function addAction( IArrowModelAction $action ){
		return $this->actions[] = $action;
	}
	
}

?>